#! /usr/bin/env python3

import argparse
import os
import subprocess

programs = [
    'astar',
    'bfbnb',
    'anytime-window-astar',
    'score',
    'dfbnb',
    'bfbnb_hash'
]

default_symlink_path = os.path.join(os.path.expanduser('~'), 'local', 'bin')

def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="This script builds the specified program.")
    parser.add_argument('program', help="The program to build.", choices=programs)
    parser.add_argument('-d', '--debug', help="If this flag is given, then the debug version "
        "of the program will be built.", action='store_true')

    parser.add_argument('-c', '--create-symlink', help="If this flag is given, then a "
        "symlink will be created at --symlink-path.", action='store_true')
    parser.add_argument('-s', '--symlink-path', help="The path where the symlink will be "
        "created.", default=default_symlink_path)
    
    parser.add_argument('--clean', help="If this flag is given, then the appropriate folders "
        "and symlinks (if specified) will be removed instead of built.", action='store_true')
    
    args = parser.parse_args()
    
    # first, run the appropriate make command
    # "/usr/bin/make" -f nbproject/Makefile-Release_astar.mk QMAKE= SUBPROJECTS= .build-conf
    release = "Release"
    if args.debug:
        release = "Debug"

    build = "build"
    if args.clean:
        build = "clean"
    
    debug = ""
    if args.debug:
        debug = "-debug"

    # check if we want to clean the symlink (we must do this before making cean)
    if args.clean:
        program = "{}{}".format(args.program, debug)
        program = os.path.join(args.symlink_path, program)
        cmd = "rm {}".format(program)
        print(cmd)
        subprocess.call(cmd, shell=True)


    cmd = "\"/usr/bin/make\" -f nbproject/Makefile-{}_{}.mk QMAKE= SUBPROJECTS= .{}-conf".format(
        release, args.program, build)
    subprocess.call(cmd, shell=True)

    # now, check on the symlink
    if not args.create_symlink:
        return

    #ln -s $PWD/dist/Release_astar/GNU-Linux/astar $HOME/local/bin/astar
    program = os.path.join(os.getcwd(), "dist", "{}_{}".format(release, args.program), "GNU-Linux", args.program)

    symlink_path = os.path.join(args.symlink_path, args.program)
    cmd = "ln -s {}{} {}".format(program, debug, symlink_path)
    print(cmd)
    subprocess.call(cmd, shell=True)


if __name__ == '__main__':
    main()
